package jco3.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;

public class SapJcoStore {

	public static Hashtable<String,JCoDestination> destinations = new Hashtable<>();
	
	public static JCoDestination getDestination(String fdPoolName) {
		JCoDestination destination = null;
		try {
			if(destinations.containsKey(fdPoolName)) {
				destination = (JCoDestination) destinations.get(fdPoolName);
			}else {
				destination = JCoDestinationManager.getDestination(fdPoolName);
				if(destination==null) {
					destination = doInitialize(fdPoolName);
				}
				destinations.put(fdPoolName, destination);
			}
		} catch (Exception e) {
			try {
				destination = doInitialize(fdPoolName);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			destinations.put(fdPoolName, destination);
		}
		return destination;
	}
	
	public Hashtable<String, JCoDestination> getDestinations(){
		return destinations;
	}
	
	public static void initStore(String poolName) throws Exception{
		doInitialize(poolName);
	}
	
	private static synchronized JCoDestination doInitialize(String fdPoolName) throws Exception{
		Properties sapConfig = new Properties();
		
		InputStream is = null;
		File file = null;
		
		file = new File("../appconfig/sap/"+fdPoolName+".properties");
		is = new FileInputStream(file);
		sapConfig.load(is);
		
		createDataFile(fdPoolName,"jcoDestination",sapConfig);
		
		JCoDestination destination = getDestination(fdPoolName);
		return destination;
	}
	
	public static void createDataFile(String name,String suffix,Properties properties) {
		File cfg = new File(name+"."+suffix);
		try {
			FileOutputStream fos = new FileOutputStream(cfg,false);
			properties.store(fos, "for connection");
			fos.close();
		} catch (Exception e) {
			throw new RuntimeException("Unable to create the destination file " +cfg.getName(),e);
		}
	}
	
}
